
import 'package:common_utils/common_utils.dart';
import 'package:get/get.dart';
import 'package:nft_shop/login/model/models.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/log_utils.dart';

class UserController extends GetxController {
  static const String kToken = 'kToken';
  static final String UserInfo = 'UserInfo';
  //用户信息
  LoginModel?  loginuser;

  static UserController get to => Get.put(UserController());

  ///是否登陆
  bool get isLogin => ObjectUtil.isNotEmpty(loginuser);

  ///获取用户信息
  Member get member => loginuser!.member!;

  ///获取token
  String token(){
    return loginuser!.token!;
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    var tokenMap = Global.box.read(kToken);
    loginuser = tokenMap != null ? LoginModel.fromJson(tokenMap) : null;

  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }


  ///保存登陆信息和token
  saveToken(LoginModel login) {
    loginuser = login;
    Log.d("-------保存token成功 --");
    Global.box.write(kToken, login);
  }

  ///保存用户信息
  saveUser(Member user) {
    loginuser!.member = user;
    Log.d("保存用户信息1---${user.toJson()}");
    Log.d("保存用户信息2---${loginuser!.member!.toJson()}");
    Global.box.write(kToken, loginuser);
    update([UserInfo]);
  }

  /// 清除持久化的用户数据
  clearUser() {
    loginuser = null;
    Global.box.remove(kToken);
    // update([UserInfo]);
  }

}